<template>
    <div class="senior">

      <el-form :model="ruleForm"
               ref="ruleForm"
               label-width="130px"
               class="demo-ruleForm">

        <div class="item-box">
          <el-form-item v-for="(item, index) in formOptions"
                        :key="index"
                        :label="item.mdName">
            <el-input v-if="!item.queryType || item.queryType === 'input'"
                      size="small"
                      v-model="ruleForm[item.mdCode]">
            </el-input>

            <!--正常的下拉选择框-->
            <el-select style="width: 100%"
                       size="small"
                       v-if="item.queryType === 'select' || item.queryType === 'multi'"
                       v-model="ruleForm[item.mdCode]"
                       :multiple="item.queryType === 'multi'"
                       placeholder="请选择">
              <el-option v-for="itemSelect in selectOptions[item.mdCode]"
                         :key="itemSelect.dictValue"
                         :label="itemSelect.dictLabel"
                         :value="itemSelect.dictValue"></el-option>
            </el-select>

            <!--范围input输入框-->
            <div class="double-input" v-if="item.queryType === 'between'">
              <el-input size="small" v-model="ruleForm[item.mdCode].begin"></el-input>
              <span>到</span>
              <el-input size="small" v-model="ruleForm[item.mdCode].end"></el-input>
            </div>

            <!--下拉树形选择框-->
            <tree-select-form v-if="item.queryType === 'org' || item.queryType === 'code'"
                              :treeData="treeOptions[item.mdCode]"
                              :treeProps="{
                                label: 'orgName',
                                value: 'id'
                             }"
                              v-model="ruleForm[item.mdCode]">
            </tree-select-form>

            <!--<tree-select v-if="item.queryType === 'org' || item.queryType === 'code'"
                         clearable
                         class="treeindex"
                         :ref="'treeSelect'"
                         style="width: 100%"
                         :options="treeOptions[item.mdCode]"
                         :props="{
                          label: 'orgName',
                          value: 'id'
                          }"
                         @getValue="getValue($event, item)">
            </tree-select>-->

            <!--年的范围选择框-->
            <year-picker-range v-if="item.queryType === 'year'"
                               :ref="'year'"
                               class="yearClear"
                               @change="handleChangeYears($event, item)">
            </year-picker-range>

            <!-- 日期范围选择框 -->
            <el-date-picker v-if="item.queryType === 'date'"
                            style="width: 100%"
                            v-model="ruleForm[item.mdCode]"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
            </el-date-picker>

            <!--时间范围选择框-->
            <el-time-picker v-if="item.queryType === 'time'"
                            is-range
                            style="width: 100%"
                            v-model="ruleForm[item.mdCode]"
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            placeholder="选择时间范围">
            </el-time-picker>

          </el-form-item>
        </div>

        <el-form-item>
          <el-button size="small" :loading="loading" type="primary" @click="submitForm">查询</el-button>
          <el-button size="small" :loading="loading" @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>

    </div>
</template>

<script>
import YearPickerRange from '../../../../../components/yearPickerRange/yearPickerRange'

import { getArchivesDicId } from '../../../../../api/dictionary/dictionary'
import { getClassificationTreeForm } from '../../../../../api/classification'
import { getQzOrg } from '../../../../../api/user/userSet'
import TreeSelectForm from '../../../../../components/treeSelect/treeSelectForm'

export default {
  name: 'retrievalSearch',
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    formItems: {
      type: Array,
      default: () => ([])
    }
  },
  components: {
    TreeSelectForm,
    YearPickerRange
  },
  data () {
    return {
      ruleForm: {},
      ops: [],
      selectOptions: {},
      treeOptions: {}
    }
  },
  computed: {
    formOptions () {
      if (this.formItems.length > 0) {
        const mdCodes = ['select', 'org', 'code']
        let opsIndex = 0
        this.formItems.map((item, index) => {
          const val = item.queryType === 'between' ? {
            begin: '',
            end: ''
          } : ''
          if (mdCodes.indexOf(item.queryType) > -1) {
            this.$set(this.ops, opsIndex, item.mdCode)
            opsIndex++
          }
          this.$set(this.ruleForm, item.mdCode, val)
        })
        this.getDic()
      }
      return this.formItems
    }
  },
  methods: {
    getDic () {
      this.formItems.map(async (item) => {
        if (item.queryType === 'select' || item.queryType === 'multi') {
          // 下拉框请求数据字典
          this.$set(this.selectOptions, item.mdCode, [])
          if (item.mdCode === 'qzh') {
            const qzData = []
            this.qzDataSelect.map(item => {
              qzData.push({
                dictLabel: item.fondsNo + ' ' + item.fondsName,
                dictValue: item.fondsNo
              })
            })
            this.$set(this.selectOptions, item.mdCode, qzData)
          } else {
            if (item.dictTypeName) {
              await getArchivesDicId(item.dictTypeName).then(res => {
                this.$set(this.selectOptions, item.mdCode, res.data.data)
              })
            } else {
              setTimeout(() => {
                this.$notify({
                  title: '提示',
                  message: '请联系管理员配置' + item.mdName + '对应数据字典！',
                  type: 'warning'
                })
              }, 500)
            }
          }
        }
        if (item.queryType === 'org' || item.queryType === 'code') {
          if (item.mdCode === 'zldw') {
            // 部门树形
            this.$set(this.treeOptions, item.mdCode, [])
            await getQzOrg().then(res => {
              this.treeOptions[item.mdCode] = res.data.data
            })
          }
          if (item.mdCode === 'flh') {
            // 分类号
            this.$set(this.treeOptions, item.mdCode, [])
            const flhQuery = {
              idCategory: this.idCategory
            }
            await getClassificationTreeForm(flhQuery).then(res => {
              this.treeOptions[item.mdCode] = []
              res.data.data.map(v => {
                this.treeOptions[item.mdCode].push({
                  orgName: v.categoryName,
                  id: v.id
                })
              })
            })
          }
        }
      })
    },
    getValue (val, item) {
      // 树形选择结果
      this.$set(this.ruleForm, item.mdCode, val)
    },
    handleChangeYears (val, item) {
      // 选择年范围
      this.$set(this.ruleForm, item.mdCode, {
        begin: val[0],
        end: val[1]
      })
    },
    async submitForm () {
      // 提交搜索
      const param = []
      Object.keys(this.ruleForm).forEach(key => {
        if (typeof (this.ruleForm[key]) === 'string' && this.ruleForm[key]) {
          param.push({
            name: key,
            op: this.ops.indexOf(key) > -1 ? 'eq' : 'like',
            value: this.ruleForm[key]
          })
        } else if (typeof (this.ruleForm[key]) === 'object') {
          if ((this.ruleForm[key] instanceof Array) && this.ruleForm[key].length > 0) {
            // 多个查询用数组
            param.push({
              name: key,
              op: 'in',
              values: this.ruleForm[key]
            })
          } else {
            // 范围组合
            if (this.ruleForm[key]) {
              if (this.ruleForm[key].begin && this.ruleForm[key].end) {
                param.push({
                  name: key,
                  op: 'ge',
                  value: this.ruleForm[key].begin
                })
                param.push({
                  name: key,
                  op: 'le',
                  value: this.ruleForm[key].end
                })
              } else if (this.ruleForm[key].begin || this.ruleForm[key].end) {
                param.push({
                  name: key,
                  op: 'eq',
                  value: this.ruleForm[key].begin || this.ruleForm[key].end
                })
              }
            }
          }
        }
      })
      this.$emit('handleSenior', param)
    },
    resetForm (formName) {
      Object.keys(this.ruleForm).forEach(key => {
        if (typeof (this.ruleForm[key]) === 'string') {
          this.$set(this.ruleForm, key, '')
        } else if (this.ruleForm[key] instanceof Array) {
          this.$set(this.ruleForm, key, [])
        } else if (typeof (this.ruleForm[key]) === 'object') {
          this.$set(this.ruleForm, key, {
            begin: '',
            end: ''
          })
        }
      })
      const yearList = document.getElementsByClassName('year')
      const treeList = document.getElementsByClassName('treeindex')
      for (let j = 0; j < treeList.length; j++) {
        this.$refs.treeSelect[j].clearHandle()
      }
      for (let i = 0; i < yearList.length; i++) {
        this.$refs.year[i].handleEmpty()
      }
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.senior{
  padding: 10px 20px;

  .item-box{
    height: calc(100vh - 150px);
    margin-right: -20px;
    padding-right: 50px;
    overflow-y: auto;
  }
  .double-input {
    display: flex;
    justify-content: space-between;

    span {
      width: 80px;
      text-align: center;
    }
  }

  ::v-deep .el-range-separator {
    min-width: 32px;
  }
}
</style>
